package pikes.peak;

import java.util.Collection;
import java.util.Map;

import org.springframework.context.NoSuchMessageException;
import org.springframework.web.servlet.support.RequestContext;

public class ApplicationContextMessageProvider implements RequestProperty<CharSequence> {

	private String key = null;

	private TextParameters textParameters = null;

	public ApplicationContextMessageProvider(final String key) {
		this(key, new TextParameters());
	}

	public ApplicationContextMessageProvider(final String key, final TextParameters textParameters) {
		this.key = key;
		this.textParameters = textParameters;
	}

	public final CharSequence getValue(Map model, RequestContext requestContext) throws Exception {
		if (key == null) {
			return null;
		}

		Collection<Object> parameters = textParameters.getValue(model, requestContext);
		Object[] parameterArray = null;
		if (parameters != null) {
			parameterArray = parameters.toArray(new Object[parameters.size()]);
		}

		try {
			return requestContext.getMessage(key, parameterArray);
		}
		catch (NoSuchMessageException noLocaleMessageException) {
			try {
				return requestContext.getThemeMessage(key, parameterArray);
			}
			catch (NoSuchMessageException noThemeMessageException) {
				return key;
			}

		}
	}

	public final String getKey() {
		return key;
	}

	public final void setKey(String key) {
		this.key = key;
	}
}
